package cn.iocoder.yudao.module.wine.service.supplyoptional;

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.wine.dal.dataobject.supplymarket.SupplyMarketDO;
import cn.iocoder.yudao.module.wine.dal.mysql.supplymarket.SupplyMarketMapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;

import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.wine.controller.app.supplyoptional.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.supplyoptional.SupplyOptionalDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wine.dal.mysql.supplyoptional.SupplyOptionalMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.*;

/**
 * 供求自选条件 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class SupplyOptionalServiceImpl implements SupplyOptionalService {

    @Resource
    private SupplyOptionalMapper supplyOptionalMapper;

    @Resource
    private SupplyMarketMapper supplyMarketMapper;

    @Resource
    private DictDataApi dataApi;

    @Override
    public Long createSupplyOptional(AppSupplyOptionalSaveReqVO createReqVO) {
        Long count = supplyOptionalMapper.selectCount(new LambdaQueryWrapperX<SupplyOptionalDO>()
                .eqIfPresent(SupplyOptionalDO::getUserId, SecurityFrameworkUtils.getLoginUserId())
                .eqIfPresent(SupplyOptionalDO::getMarketId, createReqVO.getMarketId()));
        if (count != 0L){
            throw exception(REPEAT_ADDITION);
        }
        // 插入
        SupplyOptionalDO supplyOptional = BeanUtils.toBean(createReqVO, SupplyOptionalDO.class);
        supplyOptional.setUserId(SecurityFrameworkUtils.getLoginUserId());
        supplyOptionalMapper.insert(supplyOptional);
        // 返回
        return supplyOptional.getId();
    }

    @Override
    public void updateSupplyOptional(AppSupplyOptionalSaveReqVO updateReqVO) {
        // 校验存在
        validateSupplyOptionalExists(updateReqVO.getId());
        // 更新
        SupplyOptionalDO updateObj = BeanUtils.toBean(updateReqVO, SupplyOptionalDO.class);
        supplyOptionalMapper.updateById(updateObj);
    }

    @Override
    public void deleteSupplyOptional(Long id) {
        // 校验存在
        validateSupplyOptionalExists(id);
        // 删除
        supplyOptionalMapper.deleteById(id);
    }

    private void validateSupplyOptionalExists(Long id) {
        if (supplyOptionalMapper.selectById(id) == null) {
            throw exception(INFO_NOT_EXISTS);
        }
    }

    @Override
    public SupplyOptionalDO getSupplyOptional(Long id) {
        return supplyOptionalMapper.selectById(id);
    }

    @Override
    public PageResult<SupplyOptionalDO> getSupplyOptionalPage(AppSupplyOptionalPageReqVO pageReqVO) {
        return supplyOptionalMapper.selectPage(pageReqVO);
    }

    @Override
    public List<AppSupplyOptionalRespVO> getSupplyOptionalList(AppSupplyOptionalPageReqVO pageReqVO) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        if (loginUserId!=null && loginUserId > 0) {
            List<AppSupplyOptionalRespVO> appSupplyOptionalRespVOS = supplyOptionalMapper.selectSupplyOptionalList(pageReqVO);
            if (!CollectionUtils.isEmpty(appSupplyOptionalRespVOS)) {

                List<DictDataRespDTO> packing = dataApi.getDictDataList("packing");
                List<DictDataRespDTO> year = dataApi.getDictDataList("year");

                return appSupplyOptionalRespVOS.stream().peek(item -> {
                    SupplyMarketDO supplyMarketDO = supplyMarketMapper.selectOne(new LambdaQueryWrapperX<SupplyMarketDO>()
                            .eq(SupplyMarketDO::getSupplyTypeId, item.getSupplyTypeId())
                            .eq(SupplyMarketDO::getPacking, item.getPacking())
                            .eq(SupplyMarketDO::getFragranceType, item.getFragranceType())
                            .eq(SupplyMarketDO::getShowYear, item.getShowYear())
                            .orderByDesc(SupplyMarketDO::getCountTime)
                            .last("limit 1")
                    );
                    //字典值转成字典名称
                    for (DictDataRespDTO dictDataRespDTO : packing) {
                        if (dictDataRespDTO.getValue().equals(String.valueOf(item.getPacking()))) {
                            item.setPackingName(dictDataRespDTO.getLabel());
                            break;
                        }
                    }
                    for (DictDataRespDTO dictDataRespDTO : year) {
                        if (dictDataRespDTO.getValue().equals(String.valueOf(item.getShowYear()))) {
                            item.setShowYearName(dictDataRespDTO.getLabel());
                            break;
                        }
                    }
                    ;

                    item.setAveragePrice(BigDecimal.ZERO);
                    item.setSalePrice(BigDecimal.ZERO);
                    if (supplyMarketDO != null) {
                        item.setAveragePrice(supplyMarketDO.getAveragePrice());
                        item.setSalePrice(supplyMarketDO.getSalePrice());
                    }
                }).collect(Collectors.toList());
            }
            return appSupplyOptionalRespVOS;
        }
        return null;
    }

}
